/**
 * 文档上传下载的控制器
 */
package yf.platform.ctl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.yfsoft.comm.util.ServletUtil;
import org.yfsoft.comm.util.StringUtil;
import org.yfsoft.comm.util.TimeUtil;

import yf.platform.dao.DaoExecuteException;
import yf.platform.dao.DaoSupport;


public class FileCtl extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
    private String UPLOAD_DIR = null;
    private DaoSupport dao = null;
    
	public void init(ServletConfig config) throws ServletException {
		this.dao = (DaoSupport)new ClassPathXmlApplicationContext("beans.xml").getBean("basicDao");
		Map<String,Object> settings = dao.findOne("sys_setting", "S_KEY,S_VALUE", "S_KEY = 'SYS_UPLOAD'");
		this.UPLOAD_DIR = settings.get("S_VALUE").toString();//"D:\\OA-V2\\UPLOAD\\";
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		try{
			if("upload".equals(request.getParameter("o"))){
				upload(request,response);
			}else{
				download(request,response);
			}
		}catch(DaoExecuteException dao){
			throw new ServletException(dao.getMessage());
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		doGet(request,response);
	}


//	@RequestMapping(value="/upload",method=RequestMethod.POST)
//	public String upload(HttpServletRequest req) throws Exception{
//		MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
//		MultipartFile file = mreq.getFile("file");
//		String fileName = file.getOriginalFilename();
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//		FileOutputStream fos = new FileOutputStream(req.getSession().getServletContext().getRealPath("/")+
//				"upload/"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.')));
//		fos.write(file.getBytes());
//		fos.flush();
//		fos.close();
//
//		return "hello";
//	}


	@SuppressWarnings("rawtypes")
	private void upload(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException,DaoExecuteException {
		request.setCharacterEncoding("utf8");
		response.setContentType("text/json;charset=UTF-8");
		// 解析url参数
		Map<String, String> params = ServletUtil.getParamters(request);

		// 构造一个文件上传处理对象
		ServletFileUpload upload = new ServletFileUpload( new DiskFileItemFactory());
		try {
			// 解析表单中提交的所有文件内容
			for (Iterator items = upload.parseRequest(request).iterator(); items.hasNext();) {
				FileItem item = (FileItem) items.next();
				if (!item.isFormField()) {
					// 取出上传文件的文件名称
					String name = item.getName();
					if (name.lastIndexOf("/") > -1) {
						name = name.substring(name.lastIndexOf("/"));
					}
					params.put("createtime",TimeUtil.getNow());
					params.put("title", name);
					String ext = name.substring(name.lastIndexOf(".") + 1);
					params.put("ext", ext);
					name = StringUtil.getMd5((TimeUtil.getNow() + name));
					params.put("guid", name);
					name = name+"."+ext;
					params.put("filename", name);
					// 上传文件以后的存储路径
					String path = UPLOAD_DIR+ name ;
					// 上传文件
					File uploaderFile = new File(path);
					item.write(uploaderFile);
				}
			}
			this.dao.insert( "usr_upload",params);
			response.getWriter().write("{\"code\":0,\"title\":\""+params.get("title")+"\",\"ext\":\""+params.get("ext")+"\",\"guid\":\""+params.get("guid")+"\"}");
		} catch (Exception e) {
			response.getWriter().write("{\"code\":-1,\"msg\":\""+e.getMessage()+"\"}");
		}
		
	}
	
	private void download(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException,DaoExecuteException {
		try {
            String guid = request.getParameter("guid");
            Map<String,Object> fileMap = this.dao.findOne("usr_upload","filename,title","guid = '"+guid+"'");
            File file = new File(UPLOAD_DIR+fileMap.get("filename"));
            // 取得文件名。
            String title = fileMap.get("title").toString();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(title.getBytes("utf-8"),"ISO-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
	}
}
